<!DOCTYPE html><html lang="zh-CN" data-theme="light"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no"><title>文档数据库 MongoDB_04性能优化相关 | Oct25-X</title><meta name="keywords" content="MongoDB"><meta name="author" content="Oct25-X"><meta name="copyright" content="Oct25-X"><meta name="format-detection" content="telephone=no"><meta name="theme-color" content="#ffffff"><meta name="description" content="MongoDB 性能优化对于 MongoDB 的优化可以从以下几个方面入手：  找出查询慢的语句，使用 explain() 分析 创建索引 限定返回结果，使用 limit()&#x2F;skip() 对于查询结果，只查询使用到的字段，使用 find() 方法中的 projection 控制查询结果字段 开启 profiling 优化器，记录查询时间超出指定时间的慢查询 使用 MongoTools">
<meta property="og:type" content="article">
<meta property="og:title" content="文档数据库 MongoDB_04性能优化相关">
<meta property="og:url" content="https://oct25-x.atomgit.net/oct25-xxxxx/2023/09/19/26%E6%96%87%E6%A1%A3%E6%95%B0%E6%8D%AE%E5%BA%93%20MongoDB_04%E6%80%A7%E8%83%BD%E4%BC%98%E5%8C%96%E7%9B%B8%E5%85%B3/index.html">
<meta property="og:site_name" content="Oct25-X">
<meta property="og:description" content="MongoDB 性能优化对于 MongoDB 的优化可以从以下几个方面入手：  找出查询慢的语句，使用 explain() 分析 创建索引 限定返回结果，使用 limit()&#x2F;skip() 对于查询结果，只查询使用到的字段，使用 find() 方法中的 projection 控制查询结果字段 开启 profiling 优化器，记录查询时间超出指定时间的慢查询 使用 MongoTools">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://oct25-x.atomgit.net/oct25-xxxxx/img/cover_img/ctt26.png">
<meta property="article:published_time" content="2023-09-19T08:22:18.000Z">
<meta property="article:modified_time" content="2024-02-17T14:27:41.593Z">
<meta property="article:author" content="Oct25-X">
<meta property="article:tag" content="MongoDB">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://oct25-x.atomgit.net/oct25-xxxxx/img/cover_img/ctt26.png"><link rel="shortcut icon" href="/oct25-xxxxx/img/logo.jpg"><link rel="canonical" href="https://oct25-x.atomgit.net/oct25-xxxxx/2023/09/19/26%E6%96%87%E6%A1%A3%E6%95%B0%E6%8D%AE%E5%BA%93%20MongoDB_04%E6%80%A7%E8%83%BD%E4%BC%98%E5%8C%96%E7%9B%B8%E5%85%B3/"><link rel="preconnect" href="//cdn.jsdelivr.net"/><link rel="preconnect" href="//busuanzi.ibruce.info"/><link rel="stylesheet" href="/oct25-xxxxx/css/index.css"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free@6/css/all.min.css" media="print" onload="this.media='all'"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fancyapps/ui/dist/fancybox.css" media="print" onload="this.media='all'"><script>const GLOBAL_CONFIG = { 
  root: '/oct25-xxxxx/',
  algolia: undefined,
  localSearch: {"path":"search.json","languages":{"hits_empty":"找不到您查询的内容：${query}"}},
  translate: {"defaultEncoding":2,"translateDelay":0,"msgToTraditionalChinese":"繁","msgToSimplifiedChinese":"簡"},
  noticeOutdate: undefined,
  highlight: {"plugin":"highlighjs","highlightCopy":true,"highlightLang":true,"highlightHeightLimit":false},
  copy: {
    success: '复制成功',
    error: '复制错误',
    noSupport: '浏览器不支持'
  },
  relativeDate: {
    homepage: false,
    post: false
  },
  runtime: '',
  date_suffix: {
    just: '刚刚',
    min: '分钟前',
    hour: '小时前',
    day: '天前',
    month: '个月前'
  },
  copyright: undefined,
  lightbox: 'fancybox',
  Snackbar: undefined,
  source: {
    justifiedGallery: {
      js: 'https://cdn.jsdelivr.net/npm/flickr-justified-gallery@2/dist/fjGallery.min.js',
      css: 'https://cdn.jsdelivr.net/npm/flickr-justified-gallery@2/dist/fjGallery.min.css'
    }
  },
  isPhotoFigcaption: false,
  islazyload: false,
  isAnchor: false
}</script><script id="config-diff">var GLOBAL_CONFIG_SITE = {
  title: '文档数据库 MongoDB_04性能优化相关',
  isPost: true,
  isHome: false,
  isHighlightShrink: false,
  isToc: true,
  postUpdate: '2024-02-17 22:27:41'
}</script><noscript><style type="text/css">
  #nav {
    opacity: 1
  }
  .justified-gallery img {
    opacity: 1
  }

  #recent-posts time,
  #post-meta time {
    display: inline !important
  }
</style></noscript><script>(win=>{
    win.saveToLocal = {
      set: function setWithExpiry(key, value, ttl) {
        if (ttl === 0) return
        const now = new Date()
        const expiryDay = ttl * 86400000
        const item = {
          value: value,
          expiry: now.getTime() + expiryDay,
        }
        localStorage.setItem(key, JSON.stringify(item))
      },

      get: function getWithExpiry(key) {
        const itemStr = localStorage.getItem(key)

        if (!itemStr) {
          return undefined
        }
        const item = JSON.parse(itemStr)
        const now = new Date()

        if (now.getTime() > item.expiry) {
          localStorage.removeItem(key)
          return undefined
        }
        return item.value
      }
    }
  
    win.getScript = url => new Promise((resolve, reject) => {
      const script = document.createElement('script')
      script.src = url
      script.async = true
      script.onerror = reject
      script.onload = script.onreadystatechange = function() {
        const loadState = this.readyState
        if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
        script.onload = script.onreadystatechange = null
        resolve()
      }
      document.head.appendChild(script)
    })
  
      win.activateDarkMode = function () {
        document.documentElement.setAttribute('data-theme', 'dark')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#0d0d0d')
        }
      }
      win.activateLightMode = function () {
        document.documentElement.setAttribute('data-theme', 'light')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#ffffff')
        }
      }
      const t = saveToLocal.get('theme')
    
          if (t === 'dark') activateDarkMode()
          else if (t === 'light') activateLightMode()
        
      const asideStatus = saveToLocal.get('aside-status')
      if (asideStatus !== undefined) {
        if (asideStatus === 'hide') {
          document.documentElement.classList.add('hide-aside')
        } else {
          document.documentElement.classList.remove('hide-aside')
        }
      }
    
    const detectApple = () => {
      if(/iPad|iPhone|iPod|Macintosh/.test(navigator.userAgent)){
        document.documentElement.classList.add('apple')
      }
    }
    detectApple()
    })(window)</script><link rel="stylesheet" href="/css/rightMenu.css"><meta name="generator" content="Hexo 6.1.0"></head><body><div id="sidebar"><div id="menu-mask"></div><div id="sidebar-menus"><div class="avatar-img is-center"><img src="/oct25-xxxxx/img/avatar.jpg" onerror="onerror=null;src='/img/friend_404.gif'" alt="avatar"/></div><div class="site-data is-center"><div class="data-item"><a href="/oct25-xxxxx/archives/"><div class="headline">文章</div><div class="length-num">52</div></a></div><div class="data-item"><a href="/oct25-xxxxx/tags/"><div class="headline">标签</div><div class="length-num">17</div></a></div><div class="data-item"><a href="/oct25-xxxxx/categories/"><div class="headline">分类</div><div class="length-num">8</div></a></div></div><hr/><div class="menus_items"><div class="menus_item"><a class="site-page" href="/oct25-xxxxx/"><i class="fa-fw fas fa-home"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page" href="/oct25-xxxxx/archives/"><i class="fa-fw fas fa-archive"></i><span> 归档</span></a></div><div class="menus_item"><a class="site-page" href="/oct25-xxxxx/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/oct25-xxxxx/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></div><div class="menus_item"><a class="site-page" href="/oct25-xxxxx/about/"><i class="fa-fw fas fa-heart"></i><span> 关于</span></a></div></div></div></div><div class="post" id="body-wrap"><header class="post-bg" id="page-header" style="background-image: url('/oct25-xxxxx/img/top_img/top_bg25.jpg')"><nav id="nav"><span id="blog_name"><a id="site-name" href="/oct25-xxxxx/">Oct25-X</a></span><div id="menus"><div id="search-button"><a class="site-page social-icon search"><i class="fas fa-search fa-fw"></i><span> 搜索</span></a></div><div class="menus_items"><div class="menus_item"><a class="site-page" href="/oct25-xxxxx/"><i class="fa-fw fas fa-home"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page" href="/oct25-xxxxx/archives/"><i class="fa-fw fas fa-archive"></i><span> 归档</span></a></div><div class="menus_item"><a class="site-page" href="/oct25-xxxxx/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/oct25-xxxxx/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></div><div class="menus_item"><a class="site-page" href="/oct25-xxxxx/about/"><i class="fa-fw fas fa-heart"></i><span> 关于</span></a></div></div><div id="toggle-menu"><a class="site-page"><i class="fas fa-bars fa-fw"></i></a></div></div></nav><div id="post-info"><h1 class="post-title">文档数据库 MongoDB_04性能优化相关</h1><div id="post-meta"><div class="meta-firstline"><span class="post-meta-date"><i class="far fa-calendar-alt fa-fw post-meta-icon"></i><span class="post-meta-label">发表于</span><time class="post-meta-date-created" datetime="2023-09-19T08:22:18.000Z" title="发表于 2023-09-19 16:22:18">2023-09-19</time><span class="post-meta-separator">|</span><i class="fas fa-history fa-fw post-meta-icon"></i><span class="post-meta-label">更新于</span><time class="post-meta-date-updated" datetime="2024-02-17T14:27:41.593Z" title="更新于 2024-02-17 22:27:41">2024-02-17</time></span><span class="post-meta-categories"><span class="post-meta-separator">|</span><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/oct25-xxxxx/categories/NoSQL%E6%95%B0%E6%8D%AE%E5%BA%93/">NoSQL数据库</a></span></div><div class="meta-secondline"><span class="post-meta-separator">|</span><span class="post-meta-pv-cv" id="" data-flag-title="文档数据库 MongoDB_04性能优化相关"><i class="far fa-eye fa-fw post-meta-icon"></i><span class="post-meta-label">阅读量:</span><span id="busuanzi_value_page_pv"></span></span></div></div></div></header><main class="layout" id="content-inner"><div id="post"><article class="post-content" id="article-container"><h1 id="MongoDB-性能优化"><a href="#MongoDB-性能优化" class="headerlink" title="MongoDB 性能优化"></a>MongoDB 性能优化</h1><p>对于 MongoDB 的优化可以从以下几个方面入手：</p>
<ol>
<li>找出查询慢的语句，使用 explain() 分析</li>
<li>创建索引</li>
<li>限定返回结果，使用 limit()&#x2F;skip()</li>
<li>对于查询结果，只查询使用到的字段，使用 find() 方法中的 projection 控制查询结果字段</li>
<li>开启 profiling 优化器，记录查询时间超出指定时间的慢查询</li>
<li>使用 MongoTools 工具，其中 mongostat&#x2F;mongotop 两个工具可以对 MongoDB 状态进行监控</li>
</ol>
<h1 id="explain-执行计划"><a href="#explain-执行计划" class="headerlink" title="explain() 执行计划"></a>explain() 执行计划</h1><p>首先，对于一个执行计划来说，重点主要查看以下几部分：</p>
<figure class="highlight sh"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br><span class="line">113</span><br><span class="line">114</span><br><span class="line">115</span><br><span class="line">116</span><br><span class="line">117</span><br><span class="line">118</span><br><span class="line">119</span><br><span class="line">120</span><br><span class="line">121</span><br><span class="line">122</span><br><span class="line">123</span><br><span class="line">124</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">#查询语句</span></span><br><span class="line">db.flight.find(&#123;flight: <span class="string">&quot;CA2231&quot;</span>&#125;, &#123;flight: 1, price: 1&#125;).explain(<span class="literal">true</span>)</span><br><span class="line"></span><br><span class="line"><span class="comment">#结果</span></span><br><span class="line">// 1</span><br><span class="line">&#123;</span><br><span class="line">    <span class="string">&quot;explainVersion&quot;</span>: <span class="string">&quot;1&quot;</span>,</span><br><span class="line">    <span class="string">&quot;queryPlanner&quot;</span>: &#123;</span><br><span class="line">        <span class="string">&quot;namespace&quot;</span>: <span class="string">&quot;test.flight&quot;</span>, <span class="comment">#命名空间</span></span><br><span class="line">        <span class="string">&quot;indexFilterSet&quot;</span>: <span class="literal">false</span>,</span><br><span class="line">        <span class="string">&quot;parsedQuery&quot;</span>: &#123; <span class="comment">#查询语句解析</span></span><br><span class="line">            <span class="string">&quot;flight&quot;</span>: &#123;</span><br><span class="line">                <span class="string">&quot;<span class="variable">$eq</span>&quot;</span>: <span class="string">&quot;CA2231&quot;</span></span><br><span class="line">            &#125;</span><br><span class="line">        &#125;,</span><br><span class="line">        <span class="string">&quot;maxIndexedOrSolutionsReached&quot;</span>: <span class="literal">false</span>,</span><br><span class="line">        <span class="string">&quot;maxIndexedAndSolutionsReached&quot;</span>: <span class="literal">false</span>,</span><br><span class="line">        <span class="string">&quot;maxScansToExplodeReached&quot;</span>: <span class="literal">false</span>,</span><br><span class="line">        <span class="string">&quot;winningPlan&quot;</span>: &#123; <span class="comment">#最佳执行计划，注：重点是这一部分！！！ 各阶段需要从内往外看</span></span><br><span class="line">            <span class="string">&quot;stage&quot;</span>: <span class="string">&quot;PROJECTION_SIMPLE&quot;</span>, <span class="comment">#3.使用projection限定返回字段</span></span><br><span class="line">            <span class="string">&quot;transformBy&quot;</span>: &#123;</span><br><span class="line">                <span class="string">&quot;flight&quot;</span>: 1,</span><br><span class="line">                <span class="string">&quot;price&quot;</span>: 1</span><br><span class="line">            &#125;,</span><br><span class="line">            <span class="string">&quot;inputStage&quot;</span>: &#123;</span><br><span class="line">                <span class="string">&quot;stage&quot;</span>: <span class="string">&quot;FETCH&quot;</span>, <span class="comment">#2.根据1的结果，进一步过滤抓取</span></span><br><span class="line">                <span class="string">&quot;inputStage&quot;</span>: &#123;</span><br><span class="line">                    <span class="string">&quot;stage&quot;</span>: <span class="string">&quot;IXSCAN&quot;</span>, <span class="comment">#1.使用了 IXSCAN 索引扫描</span></span><br><span class="line">                    <span class="string">&quot;keyPattern&quot;</span>: &#123;</span><br><span class="line">                        <span class="string">&quot;flight&quot;</span>: 1</span><br><span class="line">                    &#125;,</span><br><span class="line">                    <span class="string">&quot;indexName&quot;</span>: <span class="string">&quot;flight_1&quot;</span>, <span class="comment">#索引名称</span></span><br><span class="line">                    <span class="string">&quot;isMultiKey&quot;</span>: <span class="literal">false</span>,</span><br><span class="line">                    <span class="string">&quot;multiKeyPaths&quot;</span>: &#123;</span><br><span class="line">                        <span class="string">&quot;flight&quot;</span>: [ ]</span><br><span class="line">                    &#125;,</span><br><span class="line">                    <span class="string">&quot;isUnique&quot;</span>: <span class="literal">false</span>,</span><br><span class="line">                    <span class="string">&quot;isSparse&quot;</span>: <span class="literal">false</span>,</span><br><span class="line">                    <span class="string">&quot;isPartial&quot;</span>: <span class="literal">false</span>,</span><br><span class="line">                    <span class="string">&quot;indexVersion&quot;</span>: NumberInt(<span class="string">&quot;2&quot;</span>),</span><br><span class="line">                    <span class="string">&quot;direction&quot;</span>: <span class="string">&quot;forward&quot;</span>,</span><br><span class="line">                    <span class="string">&quot;indexBounds&quot;</span>: &#123; <span class="comment">#索引范围</span></span><br><span class="line">                        <span class="string">&quot;flight&quot;</span>: [</span><br><span class="line">                            <span class="string">&quot;[\&quot;CA2231\&quot;, \&quot;CA2231\&quot;]&quot;</span></span><br><span class="line">                        ]</span><br><span class="line">                    &#125;</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;,</span><br><span class="line">        <span class="string">&quot;rejectedPlans&quot;</span>: [ <span class="comment">#拒绝/淘汰执行计划</span></span><br><span class="line">            &#123;</span><br><span class="line">                <span class="string">&quot;stage&quot;</span>: <span class="string">&quot;PROJECTION_SIMPLE&quot;</span>,</span><br><span class="line">                <span class="string">&quot;transformBy&quot;</span>: &#123;</span><br><span class="line">                    <span class="string">&quot;flight&quot;</span>: 1,</span><br><span class="line">                    <span class="string">&quot;price&quot;</span>: 1</span><br><span class="line">                &#125;,</span><br><span class="line">                <span class="string">&quot;inputStage&quot;</span>: &#123;</span><br><span class="line">                    <span class="string">&quot;stage&quot;</span>: <span class="string">&quot;FETCH&quot;</span>,</span><br><span class="line">                    <span class="string">&quot;filter&quot;</span>: &#123;</span><br><span class="line">                        <span class="string">&quot;flight&quot;</span>: &#123;</span><br><span class="line">                            <span class="string">&quot;<span class="variable">$eq</span>&quot;</span>: <span class="string">&quot;CA2231&quot;</span></span><br><span class="line">                        &#125;</span><br><span class="line">                    &#125;,</span><br><span class="line">                    <span class="string">&quot;inputStage&quot;</span>: &#123;</span><br><span class="line">                        <span class="string">&quot;stage&quot;</span>: <span class="string">&quot;IXSCAN&quot;</span>, <span class="comment">#被拒绝的执行计划，先使用的为 flight_hashed 索引进行扫描</span></span><br><span class="line">                        <span class="string">&quot;keyPattern&quot;</span>: &#123;</span><br><span class="line">                            <span class="string">&quot;flight&quot;</span>: <span class="string">&quot;hashed&quot;</span></span><br><span class="line">                        &#125;,</span><br><span class="line">                        <span class="string">&quot;indexName&quot;</span>: <span class="string">&quot;flight_hashed&quot;</span>, </span><br><span class="line">                        <span class="string">&quot;isMultiKey&quot;</span>: <span class="literal">false</span>,</span><br><span class="line">                        <span class="string">&quot;isUnique&quot;</span>: <span class="literal">false</span>,</span><br><span class="line">                        <span class="string">&quot;isSparse&quot;</span>: <span class="literal">false</span>,</span><br><span class="line">                        <span class="string">&quot;isPartial&quot;</span>: <span class="literal">false</span>,</span><br><span class="line">                        <span class="string">&quot;indexVersion&quot;</span>: NumberInt(<span class="string">&quot;2&quot;</span>),</span><br><span class="line">                        <span class="string">&quot;direction&quot;</span>: <span class="string">&quot;forward&quot;</span>,</span><br><span class="line">                        <span class="string">&quot;indexBounds&quot;</span>: &#123;</span><br><span class="line">                            <span class="string">&quot;flight&quot;</span>: [</span><br><span class="line">                                <span class="string">&quot;[7910369983611535690, 7910369983611535690]&quot;</span></span><br><span class="line">                            ]</span><br><span class="line">                        &#125;</span><br><span class="line">                    &#125;</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;</span><br><span class="line">        ]</span><br><span class="line">    &#125;,</span><br><span class="line">    <span class="string">&quot;executionStats&quot;</span>: &#123; <span class="comment">#执行阶段</span></span><br><span class="line">        <span class="string">&quot;executionSuccess&quot;</span>: <span class="literal">true</span>, <span class="comment">#执行是还成功</span></span><br><span class="line">        <span class="string">&quot;nReturned&quot;</span>: NumberInt(<span class="string">&quot;3&quot;</span>), <span class="comment">#返回结果数</span></span><br><span class="line">        <span class="string">&quot;executionTimeMillis&quot;</span>: NumberInt(<span class="string">&quot;0&quot;</span>),</span><br><span class="line">        <span class="string">&quot;totalKeysExamined&quot;</span>: NumberInt(<span class="string">&quot;3&quot;</span>), <span class="comment">#索引扫描次数</span></span><br><span class="line">        <span class="string">&quot;totalDocsExamined&quot;</span>: NumberInt(<span class="string">&quot;3&quot;</span>), <span class="comment">#文档扫描次数</span></span><br><span class="line">        <span class="string">&quot;executionStages&quot;</span>: &#123;</span><br><span class="line">... ...</span><br><span class="line">        &#125;,</span><br><span class="line">... ...</span><br><span class="line">    <span class="string">&quot;command&quot;</span>: &#123; <span class="comment">#命令</span></span><br><span class="line">        <span class="string">&quot;find&quot;</span>: <span class="string">&quot;flight&quot;</span>,</span><br><span class="line">        <span class="string">&quot;filter&quot;</span>: &#123;</span><br><span class="line">            <span class="string">&quot;flight&quot;</span>: <span class="string">&quot;CA2231&quot;</span></span><br><span class="line">        &#125;,</span><br><span class="line">        <span class="string">&quot;projection&quot;</span>: &#123; <span class="comment">#限定结果字段</span></span><br><span class="line">            <span class="string">&quot;flight&quot;</span>: 1,</span><br><span class="line">            <span class="string">&quot;price&quot;</span>: 1</span><br><span class="line">        &#125;,</span><br><span class="line">        <span class="string">&quot;<span class="variable">$db</span>&quot;</span>: <span class="string">&quot;test&quot;</span></span><br><span class="line">    &#125;,</span><br><span class="line">    <span class="string">&quot;serverInfo&quot;</span>: &#123;</span><br><span class="line">        <span class="string">&quot;host&quot;</span>: <span class="string">&quot;DESKTOP-OM39JHJ&quot;</span>,</span><br><span class="line">        <span class="string">&quot;port&quot;</span>: NumberInt(<span class="string">&quot;27017&quot;</span>),</span><br><span class="line">        <span class="string">&quot;version&quot;</span>: <span class="string">&quot;5.0.13&quot;</span>,</span><br><span class="line">        <span class="string">&quot;gitVersion&quot;</span>: <span class="string">&quot;cfb7690563a3144d3d1175b3a20c2ec81b662a8f&quot;</span></span><br><span class="line">    &#125;,</span><br><span class="line">    <span class="string">&quot;serverParameters&quot;</span>: &#123;</span><br><span class="line">        <span class="string">&quot;internalQueryFacetBufferSizeBytes&quot;</span>: NumberInt(<span class="string">&quot;104857600&quot;</span>),</span><br><span class="line">        <span class="string">&quot;internalQueryFacetMaxOutputDocSizeBytes&quot;</span>: NumberInt(<span class="string">&quot;104857600&quot;</span>),</span><br><span class="line">        <span class="string">&quot;internalLookupStageIntermediateDocumentMaxSizeBytes&quot;</span>: NumberInt(<span class="string">&quot;104857600&quot;</span>),</span><br><span class="line">        <span class="string">&quot;internalDocumentSourceGroupMaxMemoryBytes&quot;</span>: NumberInt(<span class="string">&quot;104857600&quot;</span>),</span><br><span class="line">        <span class="string">&quot;internalQueryMaxBlockingSortMemoryUsageBytes&quot;</span>: NumberInt(<span class="string">&quot;104857600&quot;</span>),</span><br><span class="line">        <span class="string">&quot;internalQueryProhibitBlockingMergeOnMongoS&quot;</span>: NumberInt(<span class="string">&quot;0&quot;</span>),</span><br><span class="line">        <span class="string">&quot;internalQueryMaxAddToSetBytes&quot;</span>: NumberInt(<span class="string">&quot;104857600&quot;</span>),</span><br><span class="line">        <span class="string">&quot;internalDocumentSourceSetWindowFieldsMaxMemoryBytes&quot;</span>: NumberInt(<span class="string">&quot;104857600&quot;</span>)</span><br><span class="line">    &#125;,</span><br><span class="line">    <span class="string">&quot;ok&quot;</span>: 1</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>stage 主要为以下几种 ：</p>
<ul>
<li>COLLSACN: 全盘扫描</li>
<li>IXSACN: 索引扫描</li>
<li>FETCH: 根据前面节点扫描出的文档，进一步过滤抓取</li>
<li>SORT: 内存进行排序</li>
<li>SORT_KEY_GENERATOR: 获取每一个文档排序所用的键值</li>
<li>LIMIT: 使用limit限制返回数</li>
<li>SKIP: 使用skip进行跳过</li>
<li>IDHACK: 针对_id进行查询</li>
<li>COUNTSCAN: count不使用index进行count</li>
<li>COUNT_SCACN: count使用index进行count</li>
<li>TEXT: 使用全文索引进行查询</li>
<li>SUBPLA：未使用到索引的$or查询</li>
<li>PROJECTION：限定返回字段</li>
</ul>
<p>最佳组合 stage 如下：</p>
<ul>
<li>FETCH + IXSCAN</li>
<li>FETCH + IDHACK</li>
<li>LIMIT + ( FETCH + IXSCAN)</li>
<li>PROJECTION + IXSCAN</li>
<li>COUNT_SCAN</li>
</ul>
<p>尽量避免下面 stage 出现 :</p>
<ul>
<li>COLLSCAN</li>
<li>SORT</li>
<li>COUNTSCAN</li>
<li>SUBPLA</li>
</ul>
<h1 id="index-索引"><a href="#index-索引" class="headerlink" title="index 索引"></a>index 索引</h1><figure class="highlight sh"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">db.collection.createIndex(keys, options)</span><br></pre></td></tr></table></figure>

<p>语法中 Key 值为你要创建的索引字段，1 为指定按升序创建索引，如果你想按降序来创建索引指定为 -1 即可。</p>
<p><strong>参数说明</strong></p>
<table>
<thead>
<tr>
<th>参数</th>
<th>类型</th>
<th>描述</th>
</tr>
</thead>
<tbody><tr>
<td>background</td>
<td>Boolean</td>
<td>建索引过程会阻塞其它数据库操作，background可指定以后台方式创建索引，即增加 “background” 可选参数。 “background” 默认值为false。</td>
</tr>
<tr>
<td>unique</td>
<td>Boolean</td>
<td>建立的索引是否唯一。指定为true创建唯一索引。默认值为false。</td>
</tr>
<tr>
<td>name</td>
<td>string</td>
<td>索引的名称。如果未指定，MongoDB的通过连接索引的字段名和排序顺序生成一个索引名称。</td>
</tr>
<tr>
<td>sparse</td>
<td>Boolean</td>
<td>对文档中不存在的字段数据不启用索引；这个参数需要特别注意，如果设置为true的话，在索引字段中不会查询出不包含对应字段的文档.。默认值为 false.</td>
</tr>
<tr>
<td>expireAfterSeconds</td>
<td>integer</td>
<td>指定一个以秒为单位的数值，完成 TTL设定，设定集合的生存时间。</td>
</tr>
<tr>
<td>v</td>
<td>index version</td>
<td>索引的版本号。默认的索引版本取决于mongod创建索引时运行的版本。</td>
</tr>
<tr>
<td>weights</td>
<td>document</td>
<td>索引权重值，数值在 1 到 99,999 之间，表示该索引相对于其他索引字段的得分权重。</td>
</tr>
<tr>
<td>default_language</td>
<td>string</td>
<td>对于文本索引，该参数决定了停用词及词干和词器的规则的列表。 默认为英语</td>
</tr>
<tr>
<td>language_override</td>
<td>string</td>
<td>对于文本索引，该参数指定了包含在文档中的字段名，语言覆盖默认的language，默认值为 language.</td>
</tr>
</tbody></table>
<ol>
<li>创建索引时，可以指定后台异步创建</li>
</ol>
<figure class="highlight sh"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">db.flight.createIndex(&#123;flight: 1&#125;, &#123;background: <span class="literal">true</span>&#125;)</span><br></pre></td></tr></table></figure>

<ol start="2">
<li>创建唯一索引，类似 _id</li>
</ol>
<figure class="highlight sh"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">db.flight.createIndex(&#123;flight: 1&#125;, &#123;unique: <span class="literal">true</span>, background: <span class="literal">true</span>&#125;)</span><br></pre></td></tr></table></figure>

<ol start="3">
<li>创建复合索引</li>
</ol>
<figure class="highlight sh"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">db.flight.createIndex(&#123;flight: 1, price:　１&#125;, &#123;background: <span class="literal">true</span>&#125;)</span><br></pre></td></tr></table></figure>

<ol start="4">
<li>创建内嵌索引</li>
</ol>
<figure class="highlight sh"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">db.flight.createIndex(&#123;address.city: 1&#125;, &#123;background: <span class="literal">true</span>&#125;)</span><br><span class="line"></span><br><span class="line"><span class="comment">#注意与下面区分</span></span><br><span class="line"><span class="comment">#下面索引，需要将 province/city/district 一起使用时，索引才会起作用</span></span><br><span class="line">db.flight.createIndex(&#123;address: 1&#125;, &#123;background: <span class="literal">true</span>&#125;)</span><br></pre></td></tr></table></figure>

<ol start="5">
<li>hashed 索引</li>
</ol>
<figure class="highlight sh"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">db.flight.createIndex(&#123;flight: <span class="string">&quot;hashed&quot;</span>&#125;, &#123;background: <span class="literal">true</span>&#125;)</span><br></pre></td></tr></table></figure>

<p>需要注意的是，hashed 索引只适用于单值的完全匹配查询，不能满足范围查询</p>
<h1 id="Profiling-优化器"><a href="#Profiling-优化器" class="headerlink" title="Profiling 优化器"></a>Profiling 优化器</h1><p>MongoDB 自带一种分析工具来检测和追踪影性能的慢查询 Profiling</p>
<p>有两种方式可以控制 Profiling 的开关和级别；</p>
<ul>
<li>启动命令行或启动配置文件配置开启</li>
</ul>
<figure class="highlight sh"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">#命令行</span></span><br><span class="line"><span class="comment">#追踪级别为1，慢查询判定时间为100ms</span></span><br><span class="line"><span class="comment">#追踪级别：0不开启，1记录慢命令（默认&gt;100ms），2记录所有命令</span></span><br><span class="line">mongod --profile 1 --slowms 100</span><br><span class="line"></span><br><span class="line"><span class="comment">#将开启配置到配置文件 mongo.conf</span></span><br><span class="line">operationProfiling:</span><br><span class="line">  slowOpThresholdMs: 100</span><br><span class="line">  mode: slowOp</span><br></pre></td></tr></table></figure>

<ul>
<li>在 mongo shell 中命令开启</li>
</ul>
<figure class="highlight sh"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">#追踪级别为1，慢查询判定时间为200ms</span></span><br><span class="line">&gt; db.setProfilingLevel(1, 200)</span><br><span class="line">&#123;<span class="string">&quot;was&quot;</span>: 1, <span class="string">&quot;slowms&quot;</span>: 100, <span class="string">&quot;ok&quot;</span>: 1&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">#查询当前 profiling 状态</span></span><br><span class="line">&gt; db.<span class="function"><span class="title">getProfilingStatus</span></span>()</span><br><span class="line">&#123;<span class="string">&quot;was&quot;</span>: 1, <span class="string">&quot;slowms&quot;</span>: 100&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">#查询 profiling 级别</span></span><br><span class="line">&gt; db.getProfilingLevel()</span><br><span class="line">1</span><br></pre></td></tr></table></figure>

<p>MongoDB Profiling 慢查询记录会被记录在开启 profiling 功能的库中，集合名为：system.profile</p>
<p>所以，只需要直接查询 sytem.profile 集合即可</p>
<figure class="highlight sh"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">#直接查询</span></span><br><span class="line">db.system.profile.find()</span><br><span class="line"></span><br><span class="line"><span class="comment">#查询时间大于指定ms值的文档</span></span><br><span class="line">db.system.profile.find(&#123;millis: &#123;<span class="variable">$gt</span>: 5&#125;&#125;)</span><br><span class="line"></span><br><span class="line"><span class="comment">#按照时间戳逆序排序，查询前10条</span></span><br><span class="line">db.system.profile.find().<span class="built_in">sort</span>(&#123;ts: -1&#125;).<span class="built_in">limit</span>(10)</span><br><span class="line"></span><br><span class="line"><span class="comment">#查询指定集合数据</span></span><br><span class="line">db.system.profile.find(&#123;ns: <span class="string">&quot;test.flight&quot;</span>&#125;)</span><br></pre></td></tr></table></figure>

<p>示例</p>
<figure class="highlight sh"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br></pre></td><td class="code"><pre><span class="line">&#123;</span><br><span class="line">    <span class="string">&quot;op&quot;</span> : <span class="string">&quot;query&quot;</span>,    <span class="comment">#操作类型，有insert、query、update、remove、getmore、command   </span></span><br><span class="line">    <span class="string">&quot;ns&quot;</span> : <span class="string">&quot;mc.user&quot;</span>,  <span class="comment">#操作的集合</span></span><br><span class="line">    <span class="string">&quot;query&quot;</span> : &#123;        <span class="comment">#查询语句</span></span><br><span class="line">        <span class="string">&quot;mp_id&quot;</span> : 5,</span><br><span class="line">        <span class="string">&quot;is_fans&quot;</span> : 1,</span><br><span class="line">        <span class="string">&quot;latestTime&quot;</span> : &#123;</span><br><span class="line">            <span class="string">&quot;<span class="variable">$ne</span>&quot;</span> : 0</span><br><span class="line">        &#125;,</span><br><span class="line">        <span class="string">&quot;latestMsgId&quot;</span> : &#123;</span><br><span class="line">            <span class="string">&quot;<span class="variable">$gt</span>&quot;</span> : 0</span><br><span class="line">        &#125;,</span><br><span class="line">        <span class="string">&quot;<span class="variable">$where</span>&quot;</span> : <span class="string">&quot;new Date(this.latestNormalTime)&gt;new Date(this.replyTime)&quot;</span></span><br><span class="line">    &#125;,</span><br><span class="line">    <span class="string">&quot;cursorid&quot;</span> : NumberLong(<span class="string">&quot;1475423943124458998&quot;</span>),</span><br><span class="line">    <span class="string">&quot;ntoreturn&quot;</span> : 0,   <span class="comment">#返回的记录数。例如，profile命令将返回一个文档（一个结果文件），因此ntoreturn值将为1。limit(5)命令将返回五个文件，因此ntoreturn值是5。如果ntoreturn值为0，则该命令没有指定一些文件返回，因为会是这样一个简单的find()命令没有指定的限制。</span></span><br><span class="line">    <span class="string">&quot;ntoskip&quot;</span> : 0,     <span class="comment">#skip()方法指定的跳跃数</span></span><br><span class="line">    <span class="string">&quot;nscanned&quot;</span> : 304,  <span class="comment">#扫描数量</span></span><br><span class="line">    <span class="string">&quot;keyUpdates&quot;</span> : 0,  <span class="comment">#索引更新的数量，改变一个索引键带有一个小的性能开销，因为数据库必须删除旧的key，并插入一个新的key到B-树索引</span></span><br><span class="line">    <span class="string">&quot;numYield&quot;</span> : 0,    <span class="comment">#该查询为其他查询让出锁的次数</span></span><br><span class="line">    <span class="string">&quot;lockStats&quot;</span> : &#123;    <span class="comment">#锁信息，R：全局读锁；W：全局写锁；r：特定数据库的读锁；w：特定数据库的写锁</span></span><br><span class="line">        <span class="string">&quot;timeLockedMicros&quot;</span> : &#123;     <span class="comment">#锁</span></span><br><span class="line">            <span class="string">&quot;r&quot;</span> : NumberLong(19467),</span><br><span class="line">            <span class="string">&quot;w&quot;</span> : NumberLong(0)</span><br><span class="line">        &#125;,</span><br><span class="line">        <span class="string">&quot;timeAcquiringMicros&quot;</span> : &#123;  <span class="comment">#锁等待</span></span><br><span class="line">            <span class="string">&quot;r&quot;</span> : NumberLong(7),</span><br><span class="line">            <span class="string">&quot;w&quot;</span> : NumberLong(9)</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;,</span><br><span class="line">    <span class="string">&quot;nreturned&quot;</span> : 101,        <span class="comment">#返回的数量</span></span><br><span class="line">    <span class="string">&quot;responseLength&quot;</span> : 74659, <span class="comment">#响应字节长度</span></span><br><span class="line">    <span class="string">&quot;millis&quot;</span> : 19,            <span class="comment">#消耗的时间（毫秒）</span></span><br><span class="line">    <span class="string">&quot;ts&quot;</span> : ISODate(<span class="string">&quot;2014-02-25T02:13:54.899Z&quot;</span>), <span class="comment">#语句执行的时间</span></span><br><span class="line">    <span class="string">&quot;client&quot;</span> : <span class="string">&quot;127.0.0.1&quot;</span>,   <span class="comment">#链接ip或则主机</span></span><br><span class="line">    <span class="string">&quot;allUsers&quot;</span> : [ ],     </span><br><span class="line">    <span class="string">&quot;user&quot;</span> : <span class="string">&quot;&quot;</span>                <span class="comment">#用户</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h1 id="MongoTools"><a href="#MongoTools" class="headerlink" title="MongoTools"></a>MongoTools</h1><p>MongoTools 下载地址：<a target="_blank" rel="noopener" href="https://www.mongodb.com/try/download/database-tools">https://www.mongodb.com/try/download/database-tools</a></p>
<h2 id="mongostat"><a href="#mongostat" class="headerlink" title="mongostat"></a>mongostat</h2><p>mongostat 是 mongdb 自带的状态检测工具，提花了当前运行状态的快速概览</p>
<p>参数说明</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">mongostat </span><br><span class="line">	--host 127.0.0.1:27017  				#主机 </span><br><span class="line">	--username=zhangsan / -u=zhangsan 		#用户名</span><br><span class="line">	--password=123456 / -p123456 			#密码</span><br><span class="line">	--authenticationDatabase=test			#验证数据库</span><br><span class="line">	--rowcount=10 / -n=10					#返回指定记录行，不添加默认一直开启</span><br></pre></td></tr></table></figure>

<p>其他参数参考官网：<a target="_blank" rel="noopener" href="https://www.mongodb.com/docs/database-tools/mongostat/#options">https://www.mongodb.com/docs/database-tools/mongostat/#options</a></p>
<p>示例</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">insert query update delete getmore command dirty used flushes vsize   res qrw arw net_in net_out conn                time</span><br><span class="line">    *0    *0     *0     *0       0     0|0  0.0% 0.0%       0 5.45G 37.0M 0|0 0|0   110b   55.4k    7 Nov 22 11:11:04.921</span><br><span class="line">    *0    *0     *0     *0       0     1|0  0.0% 0.0%       0 5.45G 37.0M 0|0 0|0   112b   56.4k    7 Nov 22 11:11:05.918</span><br><span class="line">    *0    *0     *0     *0       0     0|0  0.0% 0.0%       0 5.45G 37.0M 0|0 0|0   110b   55.5k    7 Nov 22 11:11:06.930</span><br></pre></td></tr></table></figure>

<ul>
<li>insert&#x2F;query&#x2F;update&#x2F;delete：每秒增删改查次数</li>
<li>command：每秒执行命令次数，包括增删改查外，还有其他命令</li>
<li>flushes：每秒 flush 次数，将文件写入磁盘次数。一般就是0&#x2F;1，通过多个1时间判断，确定 flush 频率。</li>
<li>vsize：虚拟内存使用量，单位 MB</li>
<li>res：物理内存使用量，单位 MB</li>
<li>qrw：客户端队列中，等待读&#x2F;写的数量</li>
<li>arw：客户端执行读&#x2F;写操作的数量</li>
<li>net_in&#x2F;net_out：MongoDB 的 IO，包含 mongostat，单位 byte</li>
<li>conn：当前连接数</li>
<li>time：时间戳</li>
</ul>
<h2 id="mongotop"><a href="#mongotop" class="headerlink" title="mongotop"></a>mongotop</h2><p>mongotop 用来跟踪 MongoDB 实例，提供每个集合的统计数据，默认情况下，mongotop 每秒刷新一次</p>
<p>参数说明</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">mongotop</span><br><span class="line">	--host 127.0.0.1:27017</span><br><span class="line">	--username zhangsan</span><br><span class="line">	--password 123456</span><br><span class="line">	--authenticationDatabase admin</span><br><span class="line">	--rowcount 10</span><br></pre></td></tr></table></figure>

<p>其他参数参考官网：<a target="_blank" rel="noopener" href="https://www.mongodb.com/docs/database-tools/mongotop/#options">https://www.mongodb.com/docs/database-tools/mongotop/#options</a></p>
<p>示例</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line">                    ns    total    read    write    2022-11-23T10:03:21+08:00</span><br><span class="line">  admin.system.version      0ms     0ms      0ms</span><br><span class="line">config.system.sessions      0ms     0ms      0ms</span><br><span class="line">   config.transactions      0ms     0ms      0ms</span><br><span class="line">  local.system.replset      0ms     0ms      0ms</span><br><span class="line">             test.book      0ms     0ms      0ms</span><br><span class="line">           test.flight      0ms     0ms      0ms</span><br><span class="line">        test.fs.chunks      0ms     0ms      0ms</span><br><span class="line">         test.fs.files      0ms     0ms      0ms</span><br><span class="line">           test.person      0ms     0ms      0ms</span><br><span class="line">          test.student      0ms     0ms      0ms</span><br></pre></td></tr></table></figure>

<ul>
<li><p>ns：命名空间，就是 “数据库.集合”</p>
</li>
<li><p>total：mongod 实例，在当前命名空间上花费的总时间</p>
</li>
<li><p>read：在这个命名空间，mongod 执行读操作花费时间</p>
</li>
<li><p>write：在这个命名空间，mongod 执行写操作花费时间</p>
</li>
<li><p>当前时间</p>
</li>
</ul>
</article><div class="post-copyright"><div class="post-copyright__author"><span class="post-copyright-meta">文章作者: </span><span class="post-copyright-info"><a href="mailto:undefined">Oct25-X</a></span></div><div class="post-copyright__type"><span class="post-copyright-meta">文章链接: </span><span class="post-copyright-info"><a href="https://oct25-x.atomgit.net/oct25-xxxxx/2023/09/19/26%E6%96%87%E6%A1%A3%E6%95%B0%E6%8D%AE%E5%BA%93%20MongoDB_04%E6%80%A7%E8%83%BD%E4%BC%98%E5%8C%96%E7%9B%B8%E5%85%B3/">https://oct25-x.atomgit.net/oct25-xxxxx/2023/09/19/26%E6%96%87%E6%A1%A3%E6%95%B0%E6%8D%AE%E5%BA%93%20MongoDB_04%E6%80%A7%E8%83%BD%E4%BC%98%E5%8C%96%E7%9B%B8%E5%85%B3/</a></span></div><div class="post-copyright__notice"><span class="post-copyright-meta">版权声明: </span><span class="post-copyright-info">本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" target="_blank">CC BY-NC-SA 4.0</a> 许可协议。转载请注明来自 <a href="https://oct25-x.atomgit.net/oct25-xxxxx" target="_blank">Oct25-X</a>！</span></div></div><div class="tag_share"><div class="post-meta__tag-list"><a class="post-meta__tags" href="/oct25-xxxxx/tags/MongoDB/">MongoDB</a></div><div class="post_share"><div class="social-share" data-image="/oct25-xxxxx/img/cover_img/ctt26.png" data-sites="facebook,twitter,wechat,weibo,qq"></div><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/social-share.js/dist/css/share.min.css" media="print" onload="this.media='all'"><script src="https://cdn.jsdelivr.net/npm/social-share.js/dist/js/social-share.min.js" defer></script></div></div><nav class="pagination-post" id="pagination"><div class="prev-post pull-left"><a href="/oct25-xxxxx/2023/10/12/30%E5%88%86%E5%B8%83%E5%BC%8F%E8%B0%83%E5%BA%A6%E5%B9%B3%E5%8F%B0%20XXL-JOB/"><img class="prev-cover" src="/oct25-xxxxx/img/cover_img/ctt30.png" onerror="onerror=null;src='/oct25-xxxxx/img/404.jpg'" alt="cover of previous post"><div class="pagination-info"><div class="label">上一篇</div><div class="prev_info">分布式调度平台 XXL-JOB</div></div></a></div><div class="next-post pull-right"><a href="/oct25-xxxxx/2023/09/18/25%E6%96%87%E6%A1%A3%E6%95%B0%E6%8D%AE%E5%BA%93%20MongoDB_03SpringBoot%E6%95%B4%E5%90%88MongoDB/"><img class="next-cover" src="/oct25-xxxxx/img/cover_img/ctt25.png" onerror="onerror=null;src='/oct25-xxxxx/img/404.jpg'" alt="cover of next post"><div class="pagination-info"><div class="label">下一篇</div><div class="next_info">文档数据库 MongoDB_03SpringBoot整合MongoDB</div></div></a></div></nav><div class="relatedPosts"><div class="headline"><i class="fas fa-thumbs-up fa-fw"></i><span>相关推荐</span></div><div class="relatedPosts-list"><div><a href="/oct25-xxxxx/2023/09/02/23%E6%96%87%E6%A1%A3%E6%95%B0%E6%8D%AE%E5%BA%93%20MongoDB_01%E6%A6%82%E8%BF%B0%E4%B8%8E%E5%9F%BA%E6%9C%AC%E4%BD%BF%E7%94%A8/" title="文档数据库 MongoDB_01概述与基本使用"><img class="cover" src="/oct25-xxxxx/img/cover_img/ctt23.png" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2023-09-02</div><div class="title">文档数据库 MongoDB_01概述与基本使用</div></div></a></div><div><a href="/oct25-xxxxx/2023/09/09/24%E6%96%87%E6%A1%A3%E6%95%B0%E6%8D%AE%E5%BA%93%20MongoDB_02%E9%9B%86%E7%BE%A4%E9%83%A8%E7%BD%B2/" title="文档数据库 MongoDB_02集群部署"><img class="cover" src="/oct25-xxxxx/img/cover_img/ctt24.png" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2023-09-09</div><div class="title">文档数据库 MongoDB_02集群部署</div></div></a></div><div><a href="/oct25-xxxxx/2023/09/18/25%E6%96%87%E6%A1%A3%E6%95%B0%E6%8D%AE%E5%BA%93%20MongoDB_03SpringBoot%E6%95%B4%E5%90%88MongoDB/" title="文档数据库 MongoDB_03SpringBoot整合MongoDB"><img class="cover" src="/oct25-xxxxx/img/cover_img/ctt25.png" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2023-09-18</div><div class="title">文档数据库 MongoDB_03SpringBoot整合MongoDB</div></div></a></div></div></div></div><div class="aside-content" id="aside-content"><div class="card-widget card-info"><div class="is-center"><div class="avatar-img"><img src="/oct25-xxxxx/img/avatar.jpg" onerror="this.onerror=null;this.src='/oct25-xxxxx/img/friend_404.gif'" alt="avatar"/></div><div class="author-info__name">Oct25-X</div><div class="author-info__description"></div></div><div class="card-info-data is-center"><div class="card-info-data-item"><a href="/oct25-xxxxx/archives/"><div class="headline">文章</div><div class="length-num">52</div></a></div><div class="card-info-data-item"><a href="/oct25-xxxxx/tags/"><div class="headline">标签</div><div class="length-num">17</div></a></div><div class="card-info-data-item"><a href="/oct25-xxxxx/categories/"><div class="headline">分类</div><div class="length-num">8</div></a></div></div><a id="card-info-btn" target="_blank" rel="noopener" href="https://github.com/xxxxxx"><i class="fab fa-github"></i><span>Follow Me</span></a></div><div class="sticky_layout"><div class="card-widget" id="card-toc"><div class="item-headline"><i class="fas fa-stream"></i><span>目录</span><span class="toc-percentage"></span></div><div class="toc-content"><ol class="toc"><li class="toc-item toc-level-1"><a class="toc-link" href="#MongoDB-%E6%80%A7%E8%83%BD%E4%BC%98%E5%8C%96"><span class="toc-number">1.</span> <span class="toc-text">MongoDB 性能优化</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#explain-%E6%89%A7%E8%A1%8C%E8%AE%A1%E5%88%92"><span class="toc-number">2.</span> <span class="toc-text">explain() 执行计划</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#index-%E7%B4%A2%E5%BC%95"><span class="toc-number">3.</span> <span class="toc-text">index 索引</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#Profiling-%E4%BC%98%E5%8C%96%E5%99%A8"><span class="toc-number">4.</span> <span class="toc-text">Profiling 优化器</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#MongoTools"><span class="toc-number">5.</span> <span class="toc-text">MongoTools</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#mongostat"><span class="toc-number">5.1.</span> <span class="toc-text">mongostat</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#mongotop"><span class="toc-number">5.2.</span> <span class="toc-text">mongotop</span></a></li></ol></li></ol></div></div><div class="card-widget card-recent-post"><div class="item-headline"><i class="fas fa-history"></i><span>最新文章</span></div><div class="aside-list"><div class="aside-list-item"><a class="thumbnail" href="/oct25-xxxxx/2024/02/24/52%E5%A4%A7%E6%95%B0%E6%8D%AE%E4%B9%8B%E5%A4%9A%E8%8C%83%E5%BC%8F%E7%BC%96%E7%A8%8B%E8%AF%AD%E8%A8%80Scala09_%E9%9A%90%E5%BC%8F%E8%BD%AC%E6%8D%A2%E3%80%81%E5%BC%82%E5%B8%B8%E5%92%8C%E6%B3%9B%E5%9E%8B/" title="大数据之多范式编程语言 Scala09_隐式转换、异常和泛型"><img src="/oct25-xxxxx/img/cover_img/ctt52.png" onerror="this.onerror=null;this.src='/oct25-xxxxx/img/404.jpg'" alt="大数据之多范式编程语言 Scala09_隐式转换、异常和泛型"/></a><div class="content"><a class="title" href="/oct25-xxxxx/2024/02/24/52%E5%A4%A7%E6%95%B0%E6%8D%AE%E4%B9%8B%E5%A4%9A%E8%8C%83%E5%BC%8F%E7%BC%96%E7%A8%8B%E8%AF%AD%E8%A8%80Scala09_%E9%9A%90%E5%BC%8F%E8%BD%AC%E6%8D%A2%E3%80%81%E5%BC%82%E5%B8%B8%E5%92%8C%E6%B3%9B%E5%9E%8B/" title="大数据之多范式编程语言 Scala09_隐式转换、异常和泛型">大数据之多范式编程语言 Scala09_隐式转换、异常和泛型</a><time datetime="2024-02-24T04:55:34.000Z" title="发表于 2024-02-24 12:55:34">2024-02-24</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/oct25-xxxxx/2024/02/24/51%E5%A4%A7%E6%95%B0%E6%8D%AE%E4%B9%8B%E5%A4%9A%E8%8C%83%E5%BC%8F%E7%BC%96%E7%A8%8B%E8%AF%AD%E8%A8%80Scala08_%E6%A8%A1%E5%BC%8F%E5%8C%B9%E9%85%8D/" title="大数据之多范式编程语言 Scala08_模式匹配"><img src="/oct25-xxxxx/img/cover_img/ctt51.png" onerror="this.onerror=null;this.src='/oct25-xxxxx/img/404.jpg'" alt="大数据之多范式编程语言 Scala08_模式匹配"/></a><div class="content"><a class="title" href="/oct25-xxxxx/2024/02/24/51%E5%A4%A7%E6%95%B0%E6%8D%AE%E4%B9%8B%E5%A4%9A%E8%8C%83%E5%BC%8F%E7%BC%96%E7%A8%8B%E8%AF%AD%E8%A8%80Scala08_%E6%A8%A1%E5%BC%8F%E5%8C%B9%E9%85%8D/" title="大数据之多范式编程语言 Scala08_模式匹配">大数据之多范式编程语言 Scala08_模式匹配</a><time datetime="2024-02-24T00:46:12.000Z" title="发表于 2024-02-24 08:46:12">2024-02-24</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/oct25-xxxxx/2024/02/22/50%E5%A4%A7%E6%95%B0%E6%8D%AE%E4%B9%8B%E5%A4%9A%E8%8C%83%E5%BC%8F%E7%BC%96%E7%A8%8B%E8%AF%AD%E8%A8%80Scala07_%E9%9B%86%E5%90%88/" title="大数据之多范式编程语言 Scala07_集合"><img src="/oct25-xxxxx/img/cover_img/ctt50.png" onerror="this.onerror=null;this.src='/oct25-xxxxx/img/404.jpg'" alt="大数据之多范式编程语言 Scala07_集合"/></a><div class="content"><a class="title" href="/oct25-xxxxx/2024/02/22/50%E5%A4%A7%E6%95%B0%E6%8D%AE%E4%B9%8B%E5%A4%9A%E8%8C%83%E5%BC%8F%E7%BC%96%E7%A8%8B%E8%AF%AD%E8%A8%80Scala07_%E9%9B%86%E5%90%88/" title="大数据之多范式编程语言 Scala07_集合">大数据之多范式编程语言 Scala07_集合</a><time datetime="2024-02-22T08:16:10.000Z" title="发表于 2024-02-22 16:16:10">2024-02-22</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/oct25-xxxxx/2024/02/21/49%E5%A4%A7%E6%95%B0%E6%8D%AE%E4%B9%8B%E5%A4%9A%E8%8C%83%E5%BC%8F%E7%BC%96%E7%A8%8B%E8%AF%AD%E8%A8%80Scala06_%E9%9D%A2%E5%90%91%E5%AF%B9%E8%B1%A1/" title="大数据之多范式编程语言 Scala06_面向对象"><img src="/oct25-xxxxx/img/cover_img/ctt49.png" onerror="this.onerror=null;this.src='/oct25-xxxxx/img/404.jpg'" alt="大数据之多范式编程语言 Scala06_面向对象"/></a><div class="content"><a class="title" href="/oct25-xxxxx/2024/02/21/49%E5%A4%A7%E6%95%B0%E6%8D%AE%E4%B9%8B%E5%A4%9A%E8%8C%83%E5%BC%8F%E7%BC%96%E7%A8%8B%E8%AF%AD%E8%A8%80Scala06_%E9%9D%A2%E5%90%91%E5%AF%B9%E8%B1%A1/" title="大数据之多范式编程语言 Scala06_面向对象">大数据之多范式编程语言 Scala06_面向对象</a><time datetime="2024-02-21T07:01:10.000Z" title="发表于 2024-02-21 15:01:10">2024-02-21</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/oct25-xxxxx/2024/02/20/48%E5%A4%A7%E6%95%B0%E6%8D%AE%E4%B9%8B%E5%A4%9A%E8%8C%83%E5%BC%8F%E7%BC%96%E7%A8%8B%E8%AF%AD%E8%A8%80Scala05_%E5%87%BD%E6%95%B0%E5%BC%8F%E7%BC%96%E7%A8%8B/" title="大数据之多范式编程语言 Scala05_函数式编程"><img src="/oct25-xxxxx/img/cover_img/ctt48.png" onerror="this.onerror=null;this.src='/oct25-xxxxx/img/404.jpg'" alt="大数据之多范式编程语言 Scala05_函数式编程"/></a><div class="content"><a class="title" href="/oct25-xxxxx/2024/02/20/48%E5%A4%A7%E6%95%B0%E6%8D%AE%E4%B9%8B%E5%A4%9A%E8%8C%83%E5%BC%8F%E7%BC%96%E7%A8%8B%E8%AF%AD%E8%A8%80Scala05_%E5%87%BD%E6%95%B0%E5%BC%8F%E7%BC%96%E7%A8%8B/" title="大数据之多范式编程语言 Scala05_函数式编程">大数据之多范式编程语言 Scala05_函数式编程</a><time datetime="2024-02-20T12:05:11.000Z" title="发表于 2024-02-20 20:05:11">2024-02-20</time></div></div></div></div></div></div></main><footer id="footer" style="background-image: url('/oct25-xxxxx/img/top_img/top_bg25.jpg')"><div id="footer-wrap"><div class="copyright">&copy;2020 - 2024 By Oct25-X</div><div class="framework-info"><span>框架 </span><a target="_blank" rel="noopener" href="https://hexo.io">Hexo</a><span class="footer-separator">|</span><span>主题 </span><a target="_blank" rel="noopener" href="https://github.com/jerryc127/hexo-theme-butterfly">Butterfly</a></div></div></footer></div><div id="rightside"><div id="rightside-config-hide"><button id="readmode" type="button" title="阅读模式"><i class="fas fa-book-open"></i></button><button id="translateLink" type="button" title="简繁转换">繁</button><button id="darkmode" type="button" title="浅色和深色模式转换"><i class="fas fa-adjust"></i></button><button id="hide-aside-btn" type="button" title="单栏和双栏切换"><i class="fas fa-arrows-alt-h"></i></button></div><div id="rightside-config-show"><button id="rightside_config" type="button" title="设置"><i class="fas fa-cog fa-spin"></i></button><button class="close" id="mobile-toc-button" type="button" title="目录"><i class="fas fa-list-ul"></i></button><button id="go-up" type="button" title="回到顶部"><i class="fas fa-arrow-up"></i></button></div></div><div id="local-search"><div class="search-dialog"><nav class="search-nav"><span class="search-dialog-title">本地搜索</span><span id="loading-status"></span><button class="search-close-button"><i class="fas fa-times"></i></button></nav><div class="is-center" id="loading-database"><i class="fas fa-spinner fa-pulse"></i><span>  数据库加载中</span></div><div class="search-wrap"><div id="local-search-input"><div class="local-search-box"><input class="local-search-box--input" placeholder="搜索文章" type="text"/></div></div><hr/><div id="local-search-results"></div></div></div><div id="search-mask"></div></div><div id="rightMenu"><div class="rightMenu-group rightMenu-small"><div class="rightMenu-item" id="menu-backward"><i class="fa-solid fa-arrow-left"></i></div><div class="rightMenu-item" id="menu-forward"><i class="fa-solid fa-arrow-right"></i></div><div class="rightMenu-item" id="menu-refresh"><i class="fa-solid fa-arrow-rotate-right"></i></div><div class="rightMenu-item" id="menu-home"><i class="fa-solid fa-house"></i></div></div><div class="rightMenu-group rightMenu-line rightMenuOther"><a class="rightMenu-item menu-link" href="/archives/"><i class="fa-solid fa-archive"></i><span>文章归档</span></a><a class="rightMenu-item menu-link" href="/categories/"><i class="fa-solid fa-folder-open"></i><span>文章分类</span></a><a class="rightMenu-item menu-link" href="/tags/"><i class="fa-solid fa-tags"></i><span>文章标签</span></a></div><div class="rightMenu-group rightMenu-line rightMenuNormal"><a class="rightMenu-item" id="menu-translate"><i class="fa-solid fa-earth-asia"></i><span>繁简切换</span></a><div class="rightMenu-item" id="menu-darkmode"><i class="fa-solid fa-moon"></i><span>切换模式</span></div></div></div><div id="rightmenu-mask"></div><div><script src="/oct25-xxxxx/js/utils.js"></script><script src="/oct25-xxxxx/js/main.js"></script><script src="/oct25-xxxxx/js/tw_cn.js"></script><script src="https://cdn.jsdelivr.net/npm/@fancyapps/ui/dist/fancybox.umd.js"></script><script src="/oct25-xxxxx/js/search/local-search.js"></script><div class="js-pjax"></div><script defer src="https://npm.elemecdn.com/jquery@latest/dist/jquery.min.js"></script><script defer data-pjax src="/js/rightMenu.js"></script><script defer="defer" id="ribbon" src="https://cdn.jsdelivr.net/npm/butterfly-extsrc@1/dist/canvas-ribbon.min.js" size="150" alpha="0.6" zIndex="-1" mobile="false" data-click="true"></script><script src="https://cdn.jsdelivr.net/npm/butterfly-extsrc@1/dist/activate-power-mode.min.js"></script><script>POWERMODE.colorful = true;
POWERMODE.shake = true;
POWERMODE.mobile = false;
document.body.addEventListener('input', POWERMODE);
</script><script id="click-heart" src="https://cdn.jsdelivr.net/npm/butterfly-extsrc@1/dist/click-heart.min.js" async="async" mobile="false"></script><script async data-pjax src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script></div></body></html>